<?php

/**
 * @name /skm_www/Item.php
 * @author Kimberly Berger <knb4850@esu.edu>
 * @version
 *
 * This is the Item page.
 */

// Sets up configuration settings and includes libraries.
require_once('_ini.php');
ReqLib('/lib/private/Item.php');
ReqLib('/lib/private/User.php');
ReqLib('/lib/private/ItemSearchWidget.php');

function DefineHeader() {
?><script type="text/javascript">
	$(function() {
		$('#Replace').click(function() {
			$('#dlg').dialog('open');
		});
    // Fill the progress bars in the items table
    $.each($('.ProgressDiv'), function() {
      var $this = $(this);
      var percent = $this.find('input[type=hidden]').val() * 1;
      $this.progressbar({
        value: percent
      });
    });
		$('#ITEM').dataTable({
		  'bJQueryUI': true,
		  'sPaginationType': 'full_numbers',
		  'aaSorting': [[0, 'asc']]
		});
  });
	$(function() {
		$('#Add').dataTable({
		  'bJQueryUI': true,
		  'sPaginationType': 'full_numbers',
		  'bSort': false
		});
  });
	$(function() {
		$('#VerifyItem').dataTable({
		  'bJQueryUI': true,
		  'sPaginationType': 'full_numbers',
		  'bSort': false
		});
  });
	$(function() {
		$('#dlg').dialog({
			autoOpen: false,
			modal: true,
			width: 500,
			height: 400,
			title: 'Replacement value',
			buttons: {
				Replace: function() {
					var q = $('input[name="q"]').val();
					window.location.replace('<?=$_SERVER['PHP_SELF']?>?FItemId=<?=$_GET['FItemId']?>&name='+q);
					$(this).dialog('close');
				}
			}
		});
	});
 </script>
 <style type="text/css">
  .ProgressDiv {
    height: 15px;
  }
 </style>
<?
}
function DefinePreload(){
  $user = new User();
  $user->Load($_SESSION['userId']);
  if (!$user->UserId) {
    header('location: login_register.php?pagereq=Item.php');
	die();
	}
  if(!$user->HasRole('Administrator')){
  	header('location: login_register.php?pagereq=Item.php');
	die();
	}


	if(isset($_POST['Add'])){
	$item = new Item();
	$item->ItemId = $_POST['ItemId'];
	$item->Name = $_POST['ItemName'];
	$item->Verified = $_POST['Verified'];
	$item->Notes = $_POST['Notes'];
	$item->Quantity = $_POST['Quantity'];
	$item->EstimatedValue = $_POST['EstimatedValue'];

		if(!$item->Create($item->Name)){
			$_SESSION['Message'] = ('The item has not been added');
			header('location: Item.php');
		}
		else{
			$_SESSION['Message'] = ('The item has been added');
			header('location: Item.php');
		}
	}
	if(isset($_POST['Update'])){
		$item = new Item();
		$item->ItemId = $_POST['ItemId'];
		$item->Name = $_POST['ItemName'];
		$item->Verified = $_POST['Verified'];
		$item->Notes = $_POST['Notes'];
		$item->Quantity = $_POST['Quantity'];
		$item->EstimatedValue = $_POST['EstimatedValue'];

		if(!$item->Save()){
			$_SESSION['Message'] = ('The item has not been updated');
			header('location: Item.php');
		}
		else{
			$_SESSION['Message'] = ('The item has been updated');
			header('location: Item.php');
		}
	}

	if(isset($_POST['Delete'])){
		$item = new Item();
		$item->ItemId = $_GET['ItemId'];
		if(!$item->IsDeleteable($_GET['ItemId'])){
			$_SESSION['Message'] = ("$item->Name cannot be deleted because it is associated with a donation or a trip");
			header('location: Item.php');
		}
		else{
			if(!Item::Delete($item->ItemId)){
				$_SESSION['Message'] = "$item->Name was not deleted";
				header('location: Item.php');
			}
			else{
				$_SESSION['Message'] = 'The Item was deleted';
				header('location: Item.php');
			}
		}
	}

	if(isset($_POST['FDelete'])){
		$item = new Item();
		$item->ItemId = $_GET['FItemId'];

		$sql = "SELECT DonationId FROM donateditems WHERE ItemId ='".addslashes($item->ItemId)."';";

		$db = new DB();

		$donationId = $db->QueryVal($sql);

		if($donationId > 0){
			$sql = "DELETE FROM donateditems WHERE ItemId = '".addslashes($item->ItemId)."';";
			if($db->Query($sql)){
				$sql = "DELETE FROM items WHERE ItemId = '".addslashes($item->ItemId)."';";
				if($db->Query($sql)){
					$_SESSION['Message'] = ('The item has been deleted');
					header('location: Item.php');
				}
				else{
					$_SESSION['Message'] = ('The item has not been deleted');
					header('location: Item.php');
				}
			}
		}
		else{
			$sql = "DELETE FROM donateditems WHERE ItemId = '".addslashes($item->ItemId)."';";
			if($db->Query($sql)){
				$sql = "DELETE FROM donations WHERE DonationId = '" .$donationID. "';";
				if($db->Query($sql)){
					$sql = "DELETE FROM items WHERE ItemId = '".addslashes($item->ItemId)."';";
						if($db->Query($sql)){
							$_SESSION['Message'] = ('The item was deleted');
							header('location: Item.php');
						}
						else{
							$_SESSION['Message'] = ('The item is unable to be deleted');
							header('location: Item.php');
						}
				}
			}

		}
	}


	if(isset($_GET['name'])){
		$item = new Item();
		$item->Load($_GET['FItemId']);

		$replaceItem = new Item();
		$replaceItem->ItemId = $replaceItem->GetItemIdByItemName($_GET['name']);
		$replaceItem->Load($replaceItem->ItemId);

		$db = new DB();

		$sql = "UPDATE donateditems
				SET ItemId ='". addslashes($replaceItem->ItemId) . "'
				WHERE ItemId = '". addslashes($item->ItemId). "';";

		$db->Query($sql);
    // Add old item's quantity to replacement item
		$sql = "UPDATE items SET QuantityStored=QuantityStored+'" . addslashes($item->QuantityStored) . "' WHERE ItemId='" . addslashes($replaceItem->ItemId) . "' LIMIT 1;";
		$db->Query($sql);
		$sql = "DELETE FROM items WHERE ItemId = '".addslashes($item->ItemId)."';";

		if($db->Query($sql))
			$_SESSION['Message'] = ('The item was replaced');
		else
			$_SESSION['Message'] = ('The item was not replaced');

		header('location: Item.php?Fix');

	}

		if(isset($_POST['Verify'])){
		$item = new Item();
		$item->ItemId = $_POST['ItemId'];
		$item->Name = $_POST['ItemName'];
		$item->Verified = 1;
		$item->Notes = $_POST['Notes'];
		$item->Quantity = $_POST['Quantity'];
		$item->EstimatedValue = $_POST['EstimatedValue'];

		$sql = "SELECT ItemId from items WHERE IsVerified ='1' AND ItemName ='" . addslashes($item->Name) . "';";
		$db = new DB();
		$ids = array();
		$ids = $db->QueryCol($sql);


		if(sizeof($ids) > 0){

			$sql = "SELECT ItemId from items WHERE IsVerified ='1' AND ItemName ='" . addslashes($item->Name) . "';";

			$replaceItem = new Item();
			$VerifiedItem = $db->QueryVal($sql);

			$replaceItem->Load($VerifiedItem);

			$sql = "UPDATE items SET QuantityStored =(QuantityStored + '".addslashes($item->Quantity)."') WHERE ItemId = '". addslashes($replaceItem->ItemId)."';";
			$db->Query($sql);

			$sql = "UPDATE items SET ItemId('" . addslashes($replaceItem->ItemId) . "') FROM donateditems WHERE ItemId ='".addslashes($item->ItemId)."';";

			$db->Query($sql);

			if($VerifiedItem > 0){
				$sql = "DELETE FROM items Where ItemId = '".addslashes($item->ItemId)."';";
				if($db->Query($sql)){
					$_SESSION['Message'] = 'The item was replaced with the item of the same name. Any quantities were added';
					header('location: Item.php');
				}
				else{
					$_SESSION['Message'] = 'item was not deleted';
					header('location: Item.php');
				}
			}
			else
			{
				if(!$item->Save()){
					$_SESSION['Message'] = "The item has not been verified.";
					header('location: Item.php');
				}
				else{
					$_SESSION['Message'] = "The item has been verified.";
					header('location: Item.php');
				}
			}
		}
		else{
			if(!$item->Save()){
				$_SESSION['Message'] = "The item has not been verified.";
				header('location: Item.php');
			}
			else{
				$_SESSION['Message'] = "The item has been verified.";
				header('location: Item.php');
			}
		}
	}
}
/**
 * Defines page content.
 *
 */
function DefineContent() {
  // Page content goes here.
  ?>
<h1>Item Modification</h1>
<p>This is the Item Modification Page</p>
<p>
  <a href="<?=_webroot('/') ?>">Home</a>
</p>
<?
	if($_SESSION['userId'] >0){
?>
		<p>
		  <a href="<?=_webroot('/account.php') ?>">My Account</a>
		</p>
		<p>
		  <a href="<?=_webroot('/logout.php') ?>">Logout</a>
		</p>
<? }
   else{
?>
		<p>
		  <a href="<?=_webroot('/login_register.php') ?>">Login/Register</a>
		</p>
<?
   }
?>
  <hr />
  <center>
<?
	if(isset($_SESSION['Message'])){
		print ($_SESSION['Message'] . "<br / >");unset($_SESSION['Message']);
	}

?>
	<a href="<?=_webroot('/Item.php')?>">Item</a>
	<a href="<?=_webroot('/Item.php?Add')?>">Add Item</a>
	<a href="<?=_webroot('/Item.php?Fix')?>">Fix Unverified Items</a>

<p>
</p>


<?
	if(isset($_GET['Fix'])){
		$query = '';
		$tags = array();
		$verified = false;
		$ItemList = Item::FilteredSearch($query, $tags, $verified);
	}
	else{
		$ItemList = Item::GetItems();
	}
?>
	<div style="width: 800px; margin-left: auto; margin-right: auto;">
<?
	if(isset($_GET['Add'])){
	?>
		<center>
			<form method="POST" action="Item.php?Add">
				<table class="display" border="1" method="POST" id="Add">
					<thead>
						<th>Field</th>
						<th>Value</th>
					</thead>
					<tbody>
						<tr>
							<td>Item Name: </td>
							<td><input type="text" name="ItemName" value="<?print($item->Name)?>"/></td>
						</tr>
						<tr>
							<td>Verified Item?</td>
							<td><input type="checkbox" name="Verified" value="1" <? if(($item->Verified) == 1) print(' checked ')?> /></td>
						</tr>
						<tr>
							<td>Quantity:</td>
							<td><input type="text" name="Quantity" value="<?print($item->Quantity)?>" /></td>
						</tr>
						<tr>
							<td>Estimated Value:</td>
							<td><input type="text" name="EstimatedValue" value="<?print($item->EstimatedValue)?>" /></td>
						</tr>
						<tr>
							<td>Notes:</td>
							<td><input type="text" name="Notes" value="<?print($item->Notes)?>" /> </td>
						</tr>
						<tr>
							<td align = "right"><input type="submit" name="Add" value="Add" /></td>
							<td></td>
						</tr>
					</tbody>
				</table>
			</form>
		</center>
<?
	}
	else if($_GET['FItemId']){
		$item = new Item();
		$item->Load($_GET['FItemId']);
	?>

		<center>
			<form method="POST" action="Item.php?FItemId=<?=$item->ItemId?>">
				<table class="display" border="1" id="VerifyItem">
					<thead>
						<th>Field</th>
						<th>Value</th>
					</thead>
					<tbody>
						<tr>
							<td>Item Name: </td>
							<td><input type="hidden" name="ItemId" value="<?print($item->ItemId)?>"/><input type="text" name="ItemName" value="<?print($item->Name)?>"/></td>
						</tr>
						<tr>
							<td>Verified Item?</td>
							<td><input type="checkbox" name="Verified" value="1" <? if(($item->Verified) == 1) print(' checked ')?> /></td>
						</tr>
						<tr>
							<td>Quantity:</td>
							<td><input type="text" name="Quantity" value="<?print($item->Quantity)?>" /></td>
						</tr>
						<tr>
							<td>Estimated Value:</td>
							<td><input type="text" name="EstimatedValue" value="<?print($item->EstimatedValue)?>" /></td>
						</tr>
						<tr>
							<td>Notes:</td>
							<td><input type="text" name="Notes" value="<?print($item->Notes)?>" /> </td>
						</tr>

						<tr>
							<td align="right">
								<input type="button" id="Replace" name="Replace" value="Replace" />
								<input type="submit" name="Update" value="Update" />
							</td>
							<td align = "left">
								<input type="submit" name="Verify" value="Verify" />
								<input type="submit" name="FDelete" value="Delete" />
							</td>
						</tr>
					</tbody>
				</table>
			</form>
			<div id="dlg" style="display:none">
				<?
					$isw = new ItemSearchWidget();
					$isw->SubmitEnabled = false;
					$isw->DisplayWidget();
				?>
			</div>
		</center>
<?
	}
	else if($_GET['ItemId']){
		$item = new Item();
		$item->Load($_GET['ItemId']);
	?>

		<center>
			<form method="POST" action="Item.php?ItemId=<?=$item->ItemId?>">
				<table class="display" border="1" method="POST" id="VerifyItem">
					<thead>
						<th>Field</th>
						<th>Value</th>
					</thead>
					<tbody>
						<tr>
							<td>Item Name: </td>
							<td><input type="hidden" name="ItemId" value="<?print($item->ItemId)?>"/><input type="text" name="ItemName" value="<?print($item->Name)?>"/></td>
						</tr>
						<tr>
							<td>Verified Item?</td>
							<td><input type="checkbox" name="Verified" value="1" <? if(($item->Verified) == 1) print(' checked ')?> /></td>
						</tr>
						<tr>
							<td>Quantity:</td>
							<td><input type="text" name="Quantity" value="<?print($item->Quantity)?>" /></td>
						</tr>
						<tr>
							<td>Estimated Value:</td>
							<td><input type="text" name="EstimatedValue" value="<?print($item->EstimatedValue)?>" /></td>
						</tr>
						<tr>
							<td>Notes:</td>
							<td><input type="text" name="Notes" value="<?print($item->Notes)?>" /> </td>
						</tr>
						<tr>
							<td colspan = "2" align="center"><input type="submit" name="Update" value="Update" />
							<input type="submit" name="Delete" value="Delete" /></td>
						</tr>
					</tbody>
				</table>
			</form>
		</center>
<?
	}
	else{
?>
	<table class="display" border="1" id="ITEM">
		<thead>
			<th>ItemName</th>
			<th>Notes</th>
			<th>IsVerified</th>
			<th>Quantity</th>
			<th>Needed</th>
      <th>Supplies</th>
			<th>EstimatedValue</th>
		</thead>
	<tbody>

	<?
		if(is_array($ItemList)){
			foreach ($ItemList as $Item){
	?>
			<tr> <?if(isset($_GET['Fix'])){?>
				<td><input type="hidden" name="ItemId" value="<?print($item->ItemId)?>"/>
				<a href="Item.php?FItemId=<?=$Item->ItemId;?>"><?print($Item->Name);?></a></td>
				<?}
				else{?>
				<td><a href="Item.php?ItemId=<?=$Item->ItemId;?>"><?print($Item->Name);?></a></td>
				<?}
        $percent = min(floor($Item->Quantity * 100 / max($Item->AmountNeeded, 1) * 1),100);
  ?>
				<td><?print($Item->Notes);?></td>
				<td><?print($Item->Verified);?></td>
				<td><?print($Item->Quantity);?></td>
        <td><?print($Item->AmountNeeded);?></td>
        <td><div class="ProgressDiv"><input type="hidden" value="<?=$percent ?>" /></div></td>
				<td><?print($Item->EstimatedValue);?></td>
			</tr>

<?
			}
		?></tbody>
		<?}?>
	</table>
	</center>
<?

	}

}
// Launches the page; without this, nothing happens.
require_once('_loader.php');